#include "chatform.h"
#include "ui_chatform.h"
#include <QDebug>
#include "../wsim_client.h"
#include <QDateTime>

#include <QFontDatabase>
#include <QColorDialog>
#include <QMenu>
#include <QMovie>
#include "qmsgtextedit.h"
#include<QScrollBar>
#include <QTextBrowser>
#include "qmsgbrowser.h"
#include <QSplitter>
#include <QFileDialog>
#include "../service/wsim.h"
#include <QMessageBox>
#include "../model/collectiongrabwindow.h"

#include <unistd.h>

chatForm::chatForm(QString titleText,QString uuid,int fd,QWidget *parent) :
    MoveableFramelessDialgo(parent),
    ui(new Ui::chatForm)
{
    ui->setupUi(this);


   //setCentralWidget(splitterMain);




    initControl();
    initFontWidget();


    QSplitter *splitterMain = new QSplitter(Qt::Vertical, ui->char_main_form); //新建主分割窗口，水平分割
    QSplitter *splitterTop = new QSplitter(Qt::Vertical);

     splitterTop->addWidget(ui->chat_main_top);
     splitterTop->setStretchFactor(0,0);
    splitterTop->addWidget(ui->browserWidget);
    splitterTop->setStretchFactor(1,1);

    QSplitter *splitterBotmm = new QSplitter(Qt::Vertical);    
    splitterBotmm->addWidget(ui->editWidget);
    splitterBotmm->setStretchFactor(0,1);


   // splitterBotmm->setStretchFactor(4,0);


    splitterMain->addWidget(splitterTop);
    splitterMain->addWidget(splitterBotmm);
    splitterMain->setStretchFactor(0,1);
    splitterMain->setStretchFactor(1,0);
    splitterMain->resize(this->width()-6,this->height()-6);


    ui->label_title->setText(titleText);
    m_uuid=uuid;
    m_fd=fd;

    ui->textBrowser->verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical{width:8px;background:rgba(0,0,0,0%);margin:0px,0px,0px,0px;padding-top:9px;padding-bottom:9px;}"//留9px给上下箭头
        "QScrollBar::handle:vertical{width:8px;background:rgba(0,0,0,25%);border-radius:4px;min-height:20;}"//上下设置为椭圆
        "QScrollBar::handle:vertical:hover{width:8px;background:rgba(0,0,0,50%);border-radius:4px;min-height:20;}"//鼠标悬浮颜色变深
        "QScrollBar::add-line:vertical{height:9px;width:8px;border-image:url(:/sys/bottom.png);subcontrol-position:bottom;}"//下箭头
        "QScrollBar::sub-line:vertical{height:9px;width:8px;border-image:url(:/sys/top.png);subcontrol-position:top;}"//上箭头
        "QScrollBar::add-line:vertical:hover{height:7px;width:6px;border-image:url(:/sys/bottom.png);border:1px;subcontrol-position:bottom;}"//鼠标悬浮下箭头
        "QScrollBar::sub-line:vertical:hover{height:7px;width:6px;border-image:url(:/sys/top.png);border:1px;subcontrol-position:top;}"//鼠标悬浮上箭头
        "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:rgba(0,0,0,10%);border-radius:4px;}");//滚动时部分


    //ui->textBrowser->setStyleSheet("QTextBrowser{border-width:0;border-style:outset}");


    //关闭
    connect(ui->pushButton_close,SIGNAL(clicked()),this,SLOT(doClose()));
    connect(ui->pushButton_minbox,SIGNAL(clicked(bool)),this,SLOT(doMinbox(bool)));
    connect(ui->pushButton_clear,SIGNAL(clicked(bool)),this,SLOT(doClearSend(bool)));
    connect(ui->pushButton_sendText,SIGNAL(clicked(bool)),this,SLOT(doSendText(bool)));
    connect(ui->pushButton_font,SIGNAL(clicked(bool)),this,SLOT(doFont(bool)));
    connect(ui->pushButton_file,SIGNAL(clicked(bool)),this,SLOT(doFile(bool)));
    connect(ui->pushButton_remote,SIGNAL(clicked()),this,SLOT(doRemote()));

    connect(this, SIGNAL(loadFinished()), SLOT(onLoadFinished()));

    connect(ui->pushButton_face, SIGNAL(clicked(bool)), this, SLOT(onEmotionBtnClicked(bool)));
    connect(ui->pushButton_send, SIGNAL(clicked(bool)), this, SLOT(onSendBtnClicked(bool)));
    connect(m_emotionWindow, SIGNAL(signalEmotionWindowHide()), this, SLOT(onSetEmotionBtnStatus()));
    connect(m_emotionWindow, SIGNAL(signalEmotionItemClicked(QString)), this, SLOT(onEmotionItemClicked(QString)));

    QString fontFamily=QString::fromStdString(pConfig->getValue("Font-Family"));
    if(fontFamily.size()>0) onFontFamilycurrentIndexChanged(fontFamily);
    QString fontSize=QString::fromStdString(pConfig->getValue("Font-Size"));
    if(fontSize.size()>0) onFontSizecurrentIndexChanged(fontSize);

}

chatForm::~chatForm()
{

    m_emotionWindow->hide();
    delete m_emotionWindow;
    m_emotionWindow = nullptr;
    delete ui;
}
QWidget *chatForm::getDragnWidget()
{
    return ui->char_main_form;
}
void chatForm::doClose()
{
    this->close();
}
void chatForm::doMinbox(bool)
{
    this->showMinimized();

}

void chatForm::doFont(bool)
{
    if (ui->char_font->isVisible())
        {
            ui->char_font->setVisible(false);
            ui->pushButton_font->setChecked(false);
        }
        else
        {
            ui->char_font->setVisible(true);
            ui->pushButton_font->setChecked(true);

        }
        update();
}
void chatForm::onThemeColorChange(QString colorStr)
{
    //组合成qcc样式表
    QString style=QString("#%1{background-color:%2;}").arg(ui->centralwidget->objectName(),colorStr);
    //定义样式
    ui->centralwidget->setStyleSheet(style);

}
/**
 * @brief chatForm::onSendBtnClicked
 */
void chatForm::onSendBtnClicked(bool)
{
    //QTextDocument* document = ui->textEdit->document();
    //ui.scrollArea->scrollToBottom(ui.msgWidget);
    QString msg = ui->textEdit->toHtml();
    msg=msg.replace("\"apng-","\"");
    msg=msg.replace("-apng\"","\"");
    //WSIM_client::sendTEXT(ui->label_title->text().toStdString(),msg.toStdString());
    WSIM_client::sendTEXT_fd(m_fd,msg.toStdString());
    ui->textEdit->clear();
    ui->textEdit->delteAllEmotionImage();
    showMsg(msg);    //m_updateDownArrowtimer->start();
}
void chatForm::doSendText(bool)
{


    QString msg = ui->textEdit->toPlainText();
    if(msg.length()>0){
    //WSIM_client::sendTEXT(ui->label_title->text().toStdString(),msg.toStdString());
    WSIM_client::sendTEXT_fd(m_fd,msg.toStdString());
    ui->textEdit->clear();
    ui->textEdit->delteAllEmotionImage();
    showMsg(msg);
    }

}
/**
 * @brief chatForm::doFile 打开文件
 */
void chatForm::doFile(bool)
{
     QString m_fileName=QFileDialog::getOpenFileName(this);
        if(!m_fileName.isEmpty()){
            //ui->sendButton->setEnabled(true);
            //ui->clientStatusLabel->setText(QString("打开文件 %1 成功!").arg(m_fileName));

            //根据时间制作随机种子
            QTime time;
            time= QTime::currentTime();
            qsrand(time.msec()+time.second()*1000);
            int magic=qrand();
            WSIM_client::addLinkUp(m_fd,0,magic,m_fileName.toStdString());
            QString currentFileName="请你接收文件 ”"+m_fileName.right(m_fileName.size()-m_fileName.lastIndexOf('/')-1)+ "“ ？";
            WSIM_client::sendRequest(m_fd,magic,BINTYPE_FILE,currentFileName.toStdString());
        }


}
void chatForm::doRemote()
{
        collectionGrabWindow*pix=&(MY_COLLECTION_GRABWINDOW);
        if(pix!=NULL){
            if(!pix->isCollection()){
                uid_t uid=getuid();
                if(seteuid(0)){
                    //return -1;

                }
        QString txt=QString("请求“%1”远程协助？\n注：缺少设备控制权限时，只能向协助方播放桌面，协助方不可控制。").arg(ui->label_title->text());
    if(QMessageBox::question(this,"远程协助",txt,QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes)
    {

        //根据时间制作随机种子
        QTime time;
        time= QTime::currentTime();
        qsrand(time.msec()+time.second()*1000);
        int magic=qrand();


        QString tmpfile=QString("%1/%2_%3").arg(QDir::tempPath()).arg(m_fd).arg(magic);



           QFile* m_localFile = new QFile(tmpfile);
           QByteArray byteArray;
           if(pix->toMinByte07(byteArray))
           if(byteArray.size()>0){
                        if (!m_localFile->open(QIODevice::WriteOnly)){
                            qDebug() << "WDT_BINDATA: open file error!";
                            return;
                        }
                        else{
                                m_localFile->write(byteArray);
                            }
                            m_localFile->close();

                            WSIM_client::addTeamView(m_fd,0,magic,tmpfile.toStdString());
                            QString queststr="通过远程请求你的协助 ？";
                            WSIM_client::sendRequest(m_fd,magic,BINTYPE_TEAMVIEW,queststr.toStdString());
           }
           pix->setCollection(true);
        }

            }
            else{
                if(QMessageBox::question(this,"远程协助","结束远程协助",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes){
                pix->setCollection(false);//结束，不再采集
                }
            }
        }
}
void chatForm::doClearSend(bool)
{
    ui->textEdit->setText("");
    ui->textEdit->setHtml("");
    ui->textEdit->clear();
    ui->textEdit->delteAllEmotionImage();
}
void chatForm::onEmotionBtnClicked(bool)
{

    m_emotionWindow->setVisible(!m_emotionWindow->isVisible());
    QPoint emotionPoint = ui->pushButton_face->mapToGlobal(QPoint(0, 0));
    emotionPoint.setX(emotionPoint.x() + 0);
    emotionPoint.setY(emotionPoint.y() - 220);
    m_emotionWindow->move(emotionPoint);

}
void chatForm::onSetEmotionBtnStatus()
{
    ui->pushButton_face->setChecked(false);
}
void chatForm::onEmotionItemClicked(QString filename)
{

    ui->textEdit->setFocus();
    ui->textEdit->addEmotionUrl(filename);
}

/**
 * @brief chatForm::ReceivedMessage
 * @param msg
 */

void chatForm::ReceivedMessage(QString msg)
{
    showMsg(msg,false);
}
void chatForm::initControl()
{
    //setSendBtnMenu();
    m_emotionWindow = new EmotionWindow;
    m_emotionWindow->hide();
    /*
    QList<int> rightWidgetSize;
    rightWidgetSize << 600 << 138;
    ui.bodySpliter->setSizes(rightWidgetSize);

    m_updateDownArrowtimer = new QTimer(this);
    connect(m_updateDownArrowtimer, SIGNAL(timeout()), this, SLOT(onUpdateDownArrowtimer()));
    m_updateDownArrowtimer->setInterval(500);
    ui.scrollArea->setShowSkinControl(ui.skinLabel);
    ui.skinLabel->setSpliterButton(ui.scrollArea->getTalkWindowSpliterButton());
    */

    ui->char_font->setVisible(false);
    connect(m_emotionWindow, SIGNAL(signalEmotionItemClicked(int)), this, SLOT(onEmotionItemClicked(int)));
}

void chatForm::setSendBtnMenu()
{
    QMenu* menu = new QMenu(this);
    menu->setWindowFlags(menu->windowFlags() | Qt::FramelessWindowHint);
    menu->setAttribute(Qt::WA_TranslucentBackground);
    menu->setObjectName("senMenu");
    m_sendAction = menu->addAction(QStringLiteral("按Enter键，发送消息"), this, SLOT(onEnterAction()));
    m_ctrlSendAction = menu->addAction(QStringLiteral("按Enter+Ctrl键，发送消息"), this, SLOT(onEnterCtrlAction()));

    QActionGroup* actiongroup = new QActionGroup(this);
    m_sendAction->setCheckable(true);
    m_ctrlSendAction->setCheckable(true);
    m_sendAction->setChecked(true);
    actiongroup->addAction(m_sendAction);
    actiongroup->addAction(m_ctrlSendAction);
    ui->pushButton_send->setMenu(menu);
}

void chatForm::onEnterAction()
{
    m_sendAction->setChecked(true);
}

void chatForm::onEnterCtrlAction()
{
    m_ctrlSendAction->setChecked(true);
}
/**
 * @brief chatForm::initFontWidget 初始化字体数据
 */
void chatForm::initFontWidget()
{

    QFontDatabase fontdata;
    foreach (const QString &family,fontdata.families()) {
        ui->fontfamilyCombox->addItem(family);
    }
    for (int fontsize = 9; fontsize < 22; fontsize++)
        {
            ui->fontsizeCombox->addItem(QString::number(fontsize));
        }
        connect(ui->fontfamilyCombox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onFontFamilycurrentIndexChanged(const QString &)));
        connect(ui->fontsizeCombox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onFontSizecurrentIndexChanged(const QString &)));
        connect(ui->boldBtn, SIGNAL(clicked(bool)), this, SLOT(onBoldBtnCLicked(bool)));
        connect(ui->italBtn, SIGNAL(clicked(bool)), this, SLOT(onItalBtnCLicked(bool)));
        connect(ui->underBtn, SIGNAL(clicked(bool)), this, SLOT(onUnderBtnCLicked(bool)));
        connect(ui->colorBtn, SIGNAL(clicked(bool)), this, SLOT(onColorBtnCLicked(bool)));
        connect(ui->textEdit, &QTextEdit::currentCharFormatChanged, this, &chatForm::currentCharFormatChanged);

}

void chatForm::onFontFamilycurrentIndexChanged(const QString &family)
{
    m_font.family = family;
    QTextCharFormat fmt;
    fmt.setFontFamily(family);
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setFontFamily(family);
    ui->textEdit->setFocus();
    pConfig->setValue("Font-Family",family.toStdString());
}
void chatForm::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
{
    QTextCursor cursor = ui->textEdit->textCursor();
    if (!cursor.hasSelection())
        cursor.select(QTextCursor::Document);
    cursor.mergeCharFormat(format);
    ui->textEdit->mergeCurrentCharFormat(format);
}

void chatForm::onFontSizecurrentIndexChanged(const QString &size)
{
    m_font.fontsize = size.toInt();
    QTextCharFormat fmt;
    fmt.setFontPointSize(size.toInt());
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setFontPointSize(size.toInt());
    ui->textEdit->setFocus();
    pConfig->setValue("Font-Size",size.toStdString());
}

void chatForm::onBoldBtnCLicked(bool)
{
    QTextCharFormat fmt;
    if (ui->textEdit->fontWeight() == QFont::Bold)
    {
        m_font.bold = QFont::Normal;
        fmt.setFontWeight(QFont::Normal);
        ui->textEdit->setFontWeight(QFont::Normal);
    }
    else
    {
        m_font.bold = QFont::Bold;
        fmt.setFontWeight(QFont::Bold);
        ui->textEdit->setFontWeight(QFont::Bold);
    }
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setFocus();
}

void chatForm::onItalBtnCLicked(bool)
{
    bool ital = ui->textEdit->fontItalic();
    m_font.ital = !ital;
    QTextCharFormat fmt;
    fmt.setFontItalic(!ital);
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setFontItalic(!ital);
    ui->textEdit->setFocus();
}

void chatForm::onUnderBtnCLicked(bool)
{
    bool underline = ui->textEdit->fontUnderline();
    m_font.underline = !underline;
    QTextCharFormat fmt;
    fmt.setFontUnderline(!underline);
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setFontUnderline(!underline);
    ui->textEdit->setFocus();
}

void chatForm::onColorBtnCLicked(bool)
{
    QColorDialog colorDialog;
    QColor color = colorDialog.getColor(ui->textEdit->textColor(), this, QStringLiteral("选择字体颜色"));
    m_font.color = color;
    QTextCharFormat fmt;
    fmt.setForeground(color);
    mergeFormatOnWordOrSelection(fmt);
    ui->textEdit->setTextColor(color);
    ui->textEdit->setFocus();
}
void chatForm::currentCharFormatChanged(const QTextCharFormat &format)
{
    ui->textEdit->setFontFamily(m_font.family);
    ui->textEdit->setFontPointSize(m_font.fontsize);
    ui->textEdit->setFontWeight(m_font.bold);
    ui->textEdit->setFontItalic(m_font.ital);
    ui->textEdit->setFontUnderline(m_font.underline);
    ui->textEdit->setTextColor(m_font.color);
}

void chatForm::showMsg(QString msg,bool bsend)
{
     QString time=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
   //QString time = QString::number(QDateTime::currentDateTime().toTime_t()); //时间戳

    bool isSending = true; // 发送中

    //qDebug()<<"addMessage" << msg << time << ui->listWidget->count();
    if(bsend) {//本地

        //qDebug()<<ui->messageBrowser->size();
        ui->textBrowser->append(QString("<font color='blue' size='5'>%1</font>").arg(time));
        QString tmpstr=ui->textBrowser->giftoHtml(msg);
        ui->textBrowser->append(tmpstr);

/*
        if(isSending) {
            dealMessageTime(time);

            QNChatMessage* messageW = new QNChatMessage(ui->listWidget->parentWidget());
            QListWidgetItem* item = new QListWidgetItem(ui->listWidget);
            htmldealMessage(messageW, item, msg, time, QNChatMessage::User_Me);
        } else {
            bool isOver = true;
            for(int i = ui->listWidget->count() - 1; i > 0; i--) {
                QNChatMessage* messageW = (QNChatMessage*)ui->listWidget->itemWidget(ui->listWidget->item(i));
                if(messageW->text() == msg) {
                    isOver = false;
                    messageW->setTextSuccess();
                }
            }
            if(isOver) {
                dealMessageTime(time);

                QNChatMessage* messageW = new QNChatMessage(ui->listWidget->parentWidget());
                QListWidgetItem* item = new QListWidgetItem(ui->listWidget);
                htmldealMessage(messageW, item, msg, time, QNChatMessage::User_Me);
                messageW->setTextSuccess();
            }
        }*/
    } else {//收到的
        if(msg != "") {
        ui->textBrowser->append(QString("<font color='green' size='5'>%1 %2</font>").arg(ui->label_title->text(),time));
        QString tmpstr=ui->textBrowser->giftoHtml(msg);
        ui->textBrowser->append(tmpstr);

/*
          dealMessageTime(time);

            QNChatMessage* messageW = new QNChatMessage(ui->listWidget->parentWidget());
            QListWidgetItem* item = new QListWidgetItem(ui->listWidget);
            dealMessage(messageW, item, msg, time, QNChatMessage::User_She);
       */ }
    }
    //ui->listWidget->setCurrentRow(ui->listWidget->count()-1);
}



void chatForm::dealMessage(QNChatMessage *messageW, QListWidgetItem *item, QString text, QString time,  QNChatMessage::User_Type type)
{
/*
    messageW->setFixedWidth(this->width());
    QSize size = messageW->fontRect(text);
    item->setSizeHint(size);
    messageW->setText(text, time, size, type);
    ui->listWidget->setItemWidget(item, messageW);
    */
}

void chatForm::dealMessageTime(QString curMsgTime)
{
/*
    bool isShowTime = false;
    if(ui->listWidget->count() > 0) {
        QListWidgetItem* lastItem = ui->listWidget->item(ui->listWidget->count() - 1);
        QNChatMessage* messageW = (QNChatMessage*)ui->listWidget->itemWidget(lastItem);
        int lastTime = messageW->time().toInt();
        int curTime = curMsgTime.toInt();
        //qDebug() << "curTime lastTime:" << curTime - lastTime;
        isShowTime = ((curTime - lastTime) > 60); // 两个消息相差一分钟
        isShowTime = true;
    } else {
        isShowTime = true;
    }
    if(isShowTime) {
        QNChatMessage* messageTime = new QNChatMessage(ui->listWidget->parentWidget());
        QListWidgetItem* itemTime = new QListWidgetItem(ui->listWidget);

        QSize size = QSize(this->width(), 40);
        messageTime->resize(size);
        itemTime->setSizeHint(size);
        messageTime->setText(curMsgTime, curMsgTime, size, QNChatMessage::User_Time);
        ui->listWidget->setItemWidget(itemTime, messageTime);
    }
*/
}

void chatForm::closeEvent(QCloseEvent *event)
{
    collectionGrabWindow*pix=&(MY_COLLECTION_GRABWINDOW);
    if(pix!=NULL){
        if(pix->isCollection()){

            pix->setCollection(false);//结束，不再采集

        }
    }

}
